<template>
	<view style="height: 100%;width: 100%;" ref="mainQuestionItem">
		<!-- swiper示例 -->
		<swiper v-show="loading == false" easing-function="linear" style="height: 100%;width: 100%;"
			v-if="swiperList && swiperList.length>0" class="swiper" :duration="duration" :current="current"
			@animationfinish="itemChange">
			<swiper-item v-for="(item,index) in swiperList" :key="index">
				<view style="width: 100%;height: 100%;">
					<!-- 1. 标题 -->
					<view class="cu-bar solid-bottom" style="padding-top: 20rpx;">
						<view class="action text-black"
							style="display: flex;flex-direction: column;align-items: flex-start;">
							<span class="cuIcon-title text-black"
								style="font-weight: bold;color: #5F7E8B;">{{item.itemIndex}} 、 <span
									style="color: #646566;">
									{{item.question_name}}</span></span>
							<view v-show="item.question_image"
								style="width: 100%;max-height: 200rpx;padding-left: 20rpx;">
								<van-image height="200rpx" width="600rpx" use-error-slot fit="contain" :src="item.question_image"
									@click="imageClick(item.question_image)">
									<van-loading slot="loading" type="spinner" size="20" vertical />
									<text slot="error">加载失败【{{item.question_image}}】</text>
								</van-image>
							</view>
						</view>
					</view>

					<view style="padding: 20rpx;">
						<scroll-view :style="{ height: `calc(${transferViewHeight}px - ${300}rpx)`}"
							:scroll-top="scrollTop" scroll-y="true" class="scroll-Y">
							<van-radio-group :value="item.userAnswer" @change="radioOnChange">
								<van-cell-group :border="false">
									<van-cell v-for="option in item.optionsItems" :key="option.id" clickable
										:data-name="option.id" @click="optionOnClick(item,option)" :border="false">
										<van-radio slot="icon" :name="option.id" />
										<view slot="title">
											<block v-if="option.image">
												<van-image use-loading-slot height="150rpx" fit="heightFix"
													:src="option.image">
													<van-loading slot="loading" type="spinner" size="20" vertical />

												</van-image>
											</block>
											<block v-else>
												<span>{{option.name}}</span>
											</block>
										</view>
									</van-cell>
								</van-cell-group>
							</van-radio-group>
						</scroll-view>
					</view>
				</view>



			</swiper-item>
		</swiper>


		<!-- 悬浮按钮-->
		<view class="tn-flex  tn-footerfixed" v-show="currItemNo == transferItemList.length">
			<view class="tn-flex-1 justify-content-item tn-margin-sm tn-text-center">
				<tn-button shape="round" :disabled="btnDisabled"
					:backgroundColor="btnDisabled == true ? '#C6D1D8': 'tn-bg-blue'" padding="40rpx 0" width="60%"
					shadow fontBold @click="submitManager">
					<text class="tn-color-white">提交</text>
				</tn-button>
			</view>
		</view>


		<!-- 添加广告 -->
		<mainAd ref="mainAd" :transfer-type="'video'" @actionEventManager="adActionEventManager" />

		<view v-show="loading == true" class="tn-margin tn-text-center"
			:style="{paddingTop: vuex_custom_bar_height + 'px'}">
			<view class="">
				<view class="loading loading1 tn-icon-airplane tn-text-shadow-purplered"></view>
				<view class="loading loading2 tn-icon-flower tn-text-shadow-blue"></view>
				<view class="loading loading3 tn-icon-gift tn-text-shadow-orangered"></view>
				<view class="loading loading4 tn-icon-shop tn-text-shadow-indigo"></view>
				<view class="loading loading5 tn-icon-light tn-text-shadow-orangeyellow"></view>
				<view class="loading loading6 tn-icon-fire tn-text-shadow-cyan"></view>
			</view>
		</view>

		<!-- 选择年龄 -->
		<AgeChoose ref="AgeChoose" @actionEventManager="chooseAgeManager" />
		<!-- 选择性别  -->
		<van-action-sheet :show="genderShow" cancel-text="取消" :actions="[{ name: '男' }, { name: '女' }]" @close="genderOnClose"
			@select="genderOnSelect"  @cancel="genderOnClose"/>

		<!-- 通知 -->
		<notifyShow ref="notifyShow" />

	</view>

</template>


<script>
	import mainAd from '@/components/Ad/mainAd.vue'
	//这里引入封装的工具类方法
	import {
		initSwiper,
		leapToItem,
		changeSwiperItem,
		defaultParams
	} from '@/common/kevy-enhanced-swiper-1.0.js';
	//list -- swiper所有数据的存放列表
	//duration -- 初始化设置的过渡时间
	import notifyShow from '@/components/notifyShow.vue'

	var {
		list,
		duration
	} = defaultParams;
	//测试图片背景，这块为了测试带图片且数据量大也不存在性能问题
	const bgImg = 'https://img-blog.csdnimg.cn/140a01b8ad3f46bb9b970fdd85433ebe.png';
	import AgeChoose from '@/components/AgeChoose/AgeChoose.vue'
	export default {
		components: {
			mainAd,
			AgeChoose,
			notifyShow,
		},
		data() {
			return {
				dynamicHeight: 0,

				//  选项框的高度
				optionViewHeight: 0,

				// 0.外部传入的数据
				mainTransferItemList: [],
				// 1. 按钮 是否可以点击
				btnDisabled: true,
				// 2.加载中
				loading: true,
				// 3.是否需要年龄
				needAge: false,
				selectedAge: 0, // 选中的年龄
				// 4.是否需要性别
				needGender: false,
				selectedGender: '',
				genderShow: false,



				swiperList: [], //swiper实际列表，里面放的swiper-item数量为1-3个
				current: 0, //swiper实际列表（swiperList）中当前可以看到的那个swiper-item对应的下标，从0开始
				duration: 0, //swipper-item元素切换动画过渡时间
				currItemNo: 1, //当前显示的swiper-item在所有数据的存放列表（list）中的序号，例如总数量list里共10000条数据，currItemNo=150是指当前显示的是第150条数据

			}
		},

		mounted() {
			console.log("mounted")


		},

		onLoad(item) {
			console.log('页面加载')

		},
		onShow() {
			console.log('页面显示')
		},
		onReady() {
			console.log('页面初次显示')

		},
		onHide() {
			console.log('页面隐藏')
		},
		onUnload() {
			console.log('页面卸载')
		},
		onBackPress() {
			console.log('页面返回...')
		},
		onShareAppMessage() {
			console.log('分享!')
		},
		onReachBottom() {
			console.log('下拉加载...')
		},
		onPageScroll() {
			console.log('页面滚动...')
		},
		onPullDownRefresh() {

		},

		props: {
			transferItemList: {
				type: Array,
				default: function() {
					return []
				}
			},
			transferViewHeight: {
				type: Number,
				default: 0,
			}
		},



		watch: {
			transferViewHeight(val) {
				if (val) {
					this.dynamicHeight = val - 110;
				}
			},
		},


		methods: {
			imageClick(img) {
				wx.previewImage({
					urls: [img], //接受的是一个数组，默认展示第一张
					current: "",
					success: function(res) {},
					fail: function(res) {},
					complete: function(res) {},
				});
			},

			reload(subjectList, needAge, needGender) {
				debugger
				// 是否需要提交年龄
				if (needAge) {
					this.needAge = needAge;
				} else {
					this.needAge = false;
				}
				// 是否需要提交性别
				if (needGender) {
					this.needGender = needGender;
				} else {
					this.needGender = false;
				}




				var newItem = JSON.parse(JSON.stringify(subjectList));

				this.mainTransferItemList = newItem;
				this.mainTransferItemList.forEach((item, index) => {
					item.itemIndex = index + 1;
				});


				if (list.length) {
					list = [];
				}

				list.push(...this.mainTransferItemList);
				//请求到所有数据后放到list变量里后，初始化swiper
				initSwiper(this, list, () => {
					//这里是初始化完后的回调，你可以写自己的逻辑了，例如拿到当前swiper-item
					console.log(this.mainTransferItemList[this.current]);
					// this.loading = false;
					setTimeout(() => {
						this.loading = false;
					}, 1000);
				});

			},

			itemChange(e) {
				debugger
				changeSwiperItem(this, Number(e.detail.current), list, duration, () => {
					//切换完成
					this.currentQuestion = this.mainTransferItemList[e.detail.current];
					this.swipChangeAnimation(this.currentQuestion);
					this.$emit('actionEventManager', 'dataBack', this.currItemNo, this.currentQuestion);

				});
			},
			// 跳转到第N个
			leapTo(index) {
				leapToItem(this, index, list, duration, () => {
					//这里是跳完之后，此时页面已经显示第n个item了，
					//你可以在这里写自己的逻辑了，例如判断当前item是否收藏，是否错题...
					console.log("已经跳转到第" + index + "个item啦");
					this.currentQuestion = this.mainTransferItemList[index - 1];

					this.swipChangeAnimation(this.currentQuestion);

					this.$emit('actionEventManager', 'dataBack', this.currItemNo, this.currentQuestion);
				});
			},


			adActionEventManager(method, item, cname, realitem) {
				console.log(method, item, cname, realitem);
				if (method === 'close') {
					if (item == true) {
						// 广告播放成功
						this.$emit('actionEventManager', 'submit', {
							list: this.mainTransferItemList,
							age: this.selectedAge,
							gender:this.selectedGender
						});
					} else {

						this.$refs.notifyShow.errorOpen('请观看完成广告后获取测试结果');

					}
				}
			},

			// 1. 单选 选择
			radioOnChange(val) {
				this.mainTransferItemList[this.current].userAnswer = val;

				// 翻页
				this.cutPageManager()

			},

			cutPageManager() {
				// 1. 翻页
				debugger
				if (this.currItemNo < this.mainTransferItemList.length) {
					this.leapTo(this.currItemNo + 1);
				} else if (this.currItemNo == this.mainTransferItemList.length) {
					this.leapTo(this.currItemNo);
				}

			},


			// 2. cell 选择
			optionOnClick(item, option) {


				if (item.itemIndex == this.currItemNo) {

					// 1. 选中用户选中的答案
					this.mainOptionSelectedManager(item, option.id);

					// 1. 翻页 page + 1
					this.cutPageManager()
				}
			},

			// 选择用户选中的答案
			mainOptionSelectedManager(item, selected) {
				var currentItem = item;
				currentItem.userAnswer = selected;

				currentItem.optionsItems.forEach((optionsItem, index) => {
					if (optionsItem.id == selected) {
						if (index == 0) {
							currentItem.userAnswerType = "A";
						} else if (index == 1) {
							currentItem.userAnswerType = "B";
						} else if (index == 2) {
							currentItem.userAnswerType = "C";
						} else if (index == 3) {
							currentItem.userAnswerType = "D";
						} else if (index == 4) {
							currentItem.userAnswerType = "E";
						} else if (index == 5) {
							currentItem.userAnswerType = "F";
						} else if (index == 6) {
							currentItem.userAnswerType = "G";
						} else if (index == 7) {
							currentItem.userAnswerType = "H";
						}
						currentItem.userAnswerIndex = index;
					}
				});
			},


			// 
			swipChangeAnimation(item) {
				debugger
				if (this.currItemNo == this.mainTransferItemList.length) {
					if (item.userAnswer != '') {
						this.btnDisabled = false;
					} else {
						this.btnDisabled = true;
					}

				} else {
					this.btnDisabled = true;
				}

			},

			submitManager() {
				if (this.needGender == true) {
					this.genderShow = true;
				} else {
					this.submit1Manager();
				}
			},
			submit1Manager(){
				if (this.needAge == true) {
					this.$refs.AgeChoose.open();
				} else {
					this.$refs.mainAd.open();
				}
			},

			chooseAgeManager(method, item, cname, realitem) {
				if (method === 'selected') {
					this.selectedAge = item;
					this.$refs.mainAd.open();
				}
			},
			
			genderOnClose(){
				this.genderShow = false;
			},
			genderOnSelect(event){
				this.genderShow = false;
				this.selectedGender = event.detail.name;
				
				this.submit1Manager();
			}





		}
	}
</script>

<style lang='scss' scoped>
	@import "../../colorui/main.css";

	.scroll-Y {
		height: calc(100vh - 300rpx);

	}

	.loading {
		font-size: 60rpx;
		width: 160rpx;
		height: 160rpx;
		animation: move 3s linear infinite;
		backface-visibility: hidden;
		position: absolute;
		top: calc(50% - 160rpx);
		left: 50%;
		transform-origin: -4vmin center;
		will-change: transform;
	}

	.loading1 {
		color: #4B98FE;
		animation-delay: -0.5s;
		opacity: 0;
	}

	.loading2 {
		color: #00D05E;
		animation-delay: -1s;
		opacity: 0;
	}

	.loading3 {
		color: #FFAC00;
		animation-delay: -1.5s;
		opacity: 0;
	}

	.loading4 {
		color: #FB6A67;
		animation-delay: -2s;
		opacity: 0;
	}

	.loading5 {
		color: #957BFE;
		animation-delay: -2.5s;
		opacity: 0;
	}

	.loading6 {
		color: #00B9FE;
		animation-delay: -3s;
		opacity: 0;
	}

	@keyframes move {
		0% {
			transform: scale(1) rotate(0deg) translate3d(0, 0, 1px);
			will-change: transform;
		}

		30% {
			opacity: 1;
		}

		100% {
			z-index: 10;
			transform: scale(0) rotate(360deg) translate3d(0, 0, 1px);
			will-change: transform;
		}
	}
</style>